import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 6e4
})

service.interceptors.request.use(async req => {
  if (getToken()) req.headers['Authorization'] = `Bearer ${getToken()}`
  return req
})

service.interceptors.response.use(
  res => {
    const conf = res.config
    const data = res.data || {}
    // 未设置状态码则默认成功状态
    const status = data.code || 200
    if (status === 200) return data

    if (Object.prototype.hasOwnProperty.call(conf, status)) {
      Message.error(conf[status])
      return Promise.reject(data)
    }
    const msg = data.msg || errorCode[status] || errorCode.default
    Message.error(msg)
    return Promise.reject(data)
  },
  err => {
    const conf = err.config
    const res = err.response
    const status = err.status

    if (Object.prototype.hasOwnProperty.call(conf, status)) {
      Message.error(conf[status])
      return Promise.reject(err)
    }
    let msg = res.data?.msg || err.message || res.statusText
    if (msg === 'Network Error') msg = '网络异常，请稍后重试！'
    else if (msg.includes('timeout')) msg = '系统接口请求超时'
    else if (msg.includes('Request failed with status code')) msg = `'系统接口${msg.substr(msg.length - 3)}异常'`

    msg && Message.error(msg)
    return Promise.reject(err)
  }
)

export default {
  ...service,
  get: (url, params, opts) => service.get(url, { ...opts, params }),
  delete: (url, params, opts) => service.delete(url, { ...opts, params })
}
